<template>
  <Visible v-model="currentAnchor" :anchors="anchors">
    <div class="detail">
      <detail-header id="hidden" />
      <AnchorNav ref="anchorNav" v-model="currentAnchor" :anchors="anchors" />
      <SwipePlay v-model="currentIndex" preview :list="swipeList" />
      <Slide @left="leftHandle" @right="rightHandle">
        <div class="content">
          <div class="summary">
            <ProductName :name="detail.retrievingDes" :collectable="false" :collected="collected" @cancel-collect="cancelCollectHandle" @collect="collectHandle" @share="shareHandle" />
            <Price :price="detail.skuPrice" :price-tag="detail.skuPriceTag" />
            <div v-if="sellingPoints.length" class="show-window-tips">
              <span v-for="(tag,i) in sellingPoints" :key="i">{{ tag }}</span>
            </div>
            <div class="tags">
              <Tag :label="detail.purchaseHandle" />
              <Tag :label="detail.productState" />
              <Tag v-if="fabricChangeable" :label="fabricChangeable" />
              <template v-if="detail.mdmCode">
                <Tag v-if="sampleLoading" :label="isSample?'已上样':''" />
                <van-icon v-else name="replay" color="#009E77" size="20px" @click="getIsSample" />
              <!-- 查询失败时重新查询 -->
              </template>
            </div>
          </div>
          <div class="cell-list mb0 spuname_code">
            <Cell label="产品名称" :value="detail.mdmName || '--'" :show-ellipsis="false" :right="false" />
            <Cell label="产品编码" :value="detail.mdmCode || '--'" :show-ellipsis="false" :right="false" />
          </div>
          <div class="cell-list">
            <!-- <Cell label="选择规格" :value="attrName" weight="700" @click="clickShowHandle" /> -->
            <div v-if="detail && detail.skuId && attributes && attributes.length" class="summary border-top">
              <Attribute :sku-id="detail.skuId" :list="attributes" :skus="skus" :attr-choose="attrChoose" @list-change="attrListChange" @selected="selectedHandle" @refresh="getDetail" />
            </div>
          </div>
          <div class="desc">
            <!-- TODO:20230926 年会暂时取消
              <Card title="商品推荐">
                <Recommend :list="recommendList" @click="clickRecommendHandle" />
              </Card>
             -->
            <Card id="paramsFinished" title="规格参数">
              <ParamTable :data="params" />
            </Card>
            <Card id="descFinished" title="图文详情" :html-text="texts" />
            <Card id="introduceFinished" title="产品亮点" :html-text="saleSpeeches" />
            <Card id="abnormityDesc" title="异型说明" :html-text="abnormityDescs">
              <div v-if="['沙发','床垫','皮床','布床'].includes(spuCategoryName)" slot="after" class="html-content">
                <div class="name">温馨提示：</div>
                <div v-if="spuCategoryName==='沙发'">
                  <!-- 沙发 -->
                  <p>1、系统备注的改尺寸信息仅作销售参考，最终要以TOP系统“异型采购申请”审批为准；</p>
                  <p>2、请充分考虑沙发各部位外观加减尺寸后，单个或整体外观带来的视觉比例失调；</p>
                  <p>3、沙发加长或缩短：最少10cm起步，且必须是5cm的整数倍数（例：10cm、15cm、20cm等)；</p>
                  <p>4、独立三人位长度：不超过220cm；独立转角位（贵妃位）长度：不超过200cm；</p>
                  <p>5、若沙发单件加减尺寸异形定制均不能满足需求，可参考规格组合与尺寸加减相结合的方式；</p>
                </div>
                <div v-if="spuCategoryName==='床垫'">
                  <!-- 床垫 -->
                  <p>1、系统备注的改尺寸信息仅作销售参考，最终要以TOP系统“异型采购申请”审批为准；</p>
                  <p>2、公司已通过“常规异型”创建了产品档案，可直接采购下单，不接受改尺寸下单；</p>
                  <p>3、床垫可改尺寸的宽度：1.00M至2.00M之间；床垫可改尺寸的长度：不超过2.20M（仅8A/18097型号可做2.3米）；</p>
                  <p>4、尺寸最多精确到小数点后两位，并按末位是双数来接单。例如：1.24m*1.8m或1.18m*2.0m可接单；1.23m*2.0m或1.8m*2.03m不接单）。</p>
                </div>
                <div v-if="['皮床','布床'].includes(spuCategoryName)">
                  <!-- 软床 -->
                  <p>1、系统备注的改尺寸信息仅作销售参考，最终要以TOP系统“异型采购申请”审批为准；</p>
                  <p>2、软床异型定制改尺寸仅限1.35m*2.0m、1.5m*2.0m、1.8m*2.2m、2.0m*2.0m、2.0m*2.2m，除以上尺寸外，其他非标尺寸原则上不做异型订货，具体某个型号能做哪些尺寸，以该型号的具体说明为准；</p>
                  <p>3、 软床能做2.0*2.2m的尺寸，就可以做2.0*2.0m的尺寸；</p>
                </div>
              </div>
            </Card>
          </div>
        </div>
      </Slide>
      <!-- <Attribute v-model="show" :sku-id="detail.skuId" :list="attributes" :skus="skus" @selected="selectedHandle" @refresh="getDetail" /> -->
    </div>
    <div v-if="detail && detail.skuId" class="product-bottom-tabbar">
      <div class="to-cart-cell" @click="toCartPage">
        <van-badge :content="cartProQuantity || ''" max="99">
          <div class="icon-cart" />
        </van-badge>
      </div>
      <div class="btn-add-cart" @click="handleOpenAttrSelect">加入购物车</div>
    </div>
    <CartSheet
      v-if="showSheet"
      :show.sync="showSheet"
      :detail="detail"
      :attributes="attrList"
      :attr-choose="attrChoose"
      @refresh="getDetail"
      @success="handleAddCartSuccess"
      @fail="handleAddCartFail"
    />
    <!-- <CartSheet
      v-if="showSheet"
      :show.sync="showSheet"
      :detail="detail"
      :attributes="attributes"
      :attr-choose="attrChoose"
      @refresh="getDetail"
      @success="handleAddCartSuccess"
      @fail="handleAddCartFail"
    /> -->
    <Popup
      v-model="showError"
      msg-align="center"
      icon="error"
      :show-cancel-button="false"
      :message="errorMsg"
      @confirm="handleConfirmPop"
    />
    <PopPicker
      v-if="showShopPop"
      v-model="shareProductData.shopCode"
      title="门店"
      :show.sync="showShopPop"
      :list="userShopList"
      value-name="code"
      lable-name="name"
      :lable="shareProductData.shopName"
      @selectChange="openShare"
    />
    <ShareSheet
      v-model="showSharePop"
      @share="handleShare"
    />

  </Visible>
</template>
<script>
import ProductName from '@/components/ProductName'
import Price from '@/components/Price'
import Tag from '@/components/Tag'
import Cell from '@/components/Cell'
import Card from '@/components/Card'
import ParamTable from '@/components/ParamTable'
import AnchorNav from '@/components/AnchorNav'
import Slide from '@/components/Slide'
import Recommend from '@/components/Recommend'
import SwipePlay from '@/components/SwipePlay'
import Attribute from '@/components/Attribute'
import Visible from '@/components/Visible'
import seconds from '@/assets/seconds@2x.png'
import Popup from '@/components/Popup'
import CartSheet from './components/CartSheet'
import PopPicker from '@/components/PopPicker'
import ShareSheet from '@/components/ShareSheet'
import { info, querySpecName, querySpec, recommend, saveProductBrowsingHistory, getProductById, checkProductShareAble, setShareProduct, getCurrentUserShopList, checkIsSampleProduct } from '@/apis/productDetail'
import { queryStore } from '@/apis/order'
import { getShoppingCartCount } from '@/apis/cart'
import { formatURL } from '@/utils'
import { getBase64, cutImageBase64, dataURLtoBlob } from '@/utils/imageProcessing'
export default {
  name: 'FinishedDetail',
  components: {
    ProductName,
    Price,
    Tag,
    Cell,
    Card,
    ParamTable,
    AnchorNav,
    Slide,
    Recommend,
    Attribute,
    SwipePlay,
    Visible,
    Popup,
    CartSheet,
    PopPicker,
    ShareSheet
  },
  props: {
    spuId: {
      type: String,
      required: true
    },
    skuId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      fromRouteName: '', // 来源路由
      currentIndex: 0,
      // 图标
      seconds,
      // 是否已收藏
      collected: false,
      // 导航
      currentAnchor: 'hidden',
      anchors: [
        { label: '规格参数', value: 'paramsFinished' },
        { label: '图文详情', value: 'descFinished' },
        { label: '产品亮点', value: 'introduceFinished' },
        { label: '异型说明', value: 'abnormityDesc' }
      ],
      detail: {},
      // 规格属性
      attributes: [],
      attrChoose: [],
      show: false,
      attrSelected: null,
      // 详情
      querySpec: {},
      // 推荐
      recommend: [],
      cartProQuantity: 0, // 购物车商品数量
      attrList: [], // 组合后的规格属性列表
      showSheet: false, // 是否打开加入购物车面板
      showError: false, // 是否显示加入购物车
      errorMsg: '', // 加入购物车的错误提示
      brownHistorySku: '', // 预览记录的sku，临时存储
      spuDetail: '',
      userShopList: [
        /* { code: '1111', name: '测试门店1' } */
      ], // 当前用户所挂门店组织
      showShopPop: false, // 是否显示门店选择器
      showSharePop: false, // 是否显示分享面板
      shareSkuId: '',
      shareProductData: {
        // 分享商品数据
        mdmCode: '',
        mdmName: '',
        productCode: '',
        productId: '',
        productName: '',
        shopCode: '',
        shopName: '',
        skuId: '',
        skuCode: '',
        skuName: ''
      },
      sampleLoading: false, // 是否已加载上样
      isSample: false // 是否上样产品
    }
  },
  computed: {
    fabricChangeable() {
      const y = this.detail.fabricChangeable
      if (y === 'Y') {
        return '可换面料'
      } else if (y === 'N') {
        // return '不可换面料'
        return ''
      }
      return ''
    },
    spuCategoryName() {
      return this.spuDetail?.productCategoryName
    },
    swipeList() {
      let mainPic = ''
      const list = (this.detail.pics || []).map(e => {
        e.src = e.picUrl
        e.type = 'image'
        if (e.mainPicFlag === 'Y') {
          mainPic = e.picUrl
        }
        return e
      })
      if (this.detail.mainVideo) {
        list.unshift({
          src: this.detail.mainVideo,
          poster: mainPic,
          type: 'video'
        })
      }
      // ====== 测试视频 =====
      // list.unshift({
      //   src: 'https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-720p.mp4',
      //   poster: 'https://s2.pstatp.com/cdn/expire-1-M/byted-player-videos/1.0.0/poster.jpg',
      //   type: 'video'
      // })
      // =====
      return list
    },
    recommendList() {
      return (this.recommend || []).map(e => {
        e.src = e.pic
        e.type = 'image'
        e.label = e.skuName
        return e
      })
    },
    params() {
      return (this.querySpec.values || []).map(e => {
        e.label = e.key
        return e
      })
    },
    // 介绍
    saleSpeeches() {
      return this.querySpec.saleSpeeches
    },
    // 异型说明
    abnormityDescs() {
      return this.querySpec.abnormityDescs
    },
    // 图文
    texts() {
      return this.querySpec.texts
    },
    skus() {
      return this.detail.skus || []
    },
    // 选中的属性
    attrName() {
      return this.attrSelected ? Object.values(this.attrSelected).map(e => e.value).join('/') : ''
    },
    sellingPoints() {
      if (this.detail.sellingPoints && this.detail.sellingPoints.length) {
        return this.detail.sellingPoints.filter(v => ![null, undefined, ''].includes(v))
      }
      return []
    }
  },
  watch: {

  },
  created() {
    this.getCartCount()
    this.getDetail()
    this.getSpuDetailInfo()
  },
  methods: {
    // 获取详情
    getDetail(skuId) {
      skuId = skuId || this.skuId
      this.shareSkuId = skuId
      const promiseList = []
      promiseList.push(info(this.spuId, skuId))// 详情
      promiseList.push(querySpecName(this.spuId))// 规格属性
      promiseList.push(querySpec(skuId))// 图文详情
      Promise.all(promiseList).then((res) => {
        this.detail = res[0].data
        // console.log(this.detail)
        if (this.brownHistorySku !== skuId) {
          this.setBrowsingHistory(skuId)
        }
        this.attrChoose = this.detail.attrChooseDTOS
        this.attributes = res[1].data
        this.querySpec = res[2].data
        this.getIsSample()
      })
      // 推荐
      // this.getRecommend(skuId) //TODO:20230926 年会暂时取消
      /* info(this.spuId, skuId).then(res => {
        this.detail = res.data
        this.attrChoose = this.detail.attrChooseDTOS
        // 规格属性
        querySpecName(this.spuId).then(res => {
          this.attributes = res.data
        })
        // 图文详情
        querySpec(skuId).then(res => {
          this.querySpec = res.data
        })
        // 推荐
        this.getRecommend(skuId)
      }) */
    },

    getSpuDetailInfo() {
      getProductById(this.spuId).then(res => {
        this.spuDetail = res.data || ''
      })
    },
    // 判断商品是否为上样产品
    async getIsSample() {
      // TODO: 上样等老王发了再发
      this.sampleLoading = true
      return
      const mdmCode = this.detail.mdmCode || ''
      if (!mdmCode) return
      let flag = false
      await checkIsSampleProduct(mdmCode).then(res => {
        if (res.success === 1) {
          flag = res && res.data === true
          this.sampleLoading = true
        }
      })
      this.isSample = flag
    },
    // 保存浏览记录
    setBrowsingHistory(skuId) {
      const skus = this.detail.skus || []
      const sku = skus.find(v => v.id === skuId)
      if (!sku || !sku.skuCode) {
        return
      }
      const { skuCode, skuName } = sku
      const data = {
        mdmCode: this.detail.mdmCode || '',
        skuCode,
        skuName
      }
      saveProductBrowsingHistory(data).then(res => {
        this.brownHistorySku = skuId
      })
    },
    // 获取推荐
    getRecommend(skuId) {
      recommend(skuId).then(res => {
        this.recommend = res.data
      })
    },
    // 取消收藏
    cancelCollectHandle() {
      this.collected = false
    },
    // 收藏
    collectHandle() {
      this.collected = true
    },
    // 推荐
    clickRecommendHandle(item) {
      this.$router.replace({ name: 'FinishedDetail', params: { spuId: item.productId, skuId: item.skuId }})
    },
    // 显示属性
    clickShowHandle() {
      this.show = !this.show
    },
    // 规格属性选取
    selectedHandle(item) {
      this.attrSelected = item
    },
    // 锚点切换
    // 获取下一个锚点
    getAnchor(left = true) {
      for (let i = 0; i < this.anchors.length; i++) {
        const a = this.anchors[i]
        if (a.value === this.currentAnchor) {
          if (left) {
            if (i + 1 > this.anchors.length - 1) {
              return this.anchors[0]
            } else {
              return this.anchors[i + 1]
            }
          } else {
            if (i - 1 < 0) {
              return this.anchors[this.anchors.length - 1]
            } else {
              return this.anchors[i - 1]
            }
          }
        }
      }
    },
    leftHandle() {
      const a = this.getAnchor(true)
      if (a) {
        this.$refs.anchorNav.clickHandle(a)
      }
    },
    rightHandle() {
      const a = this.getAnchor(false)
      if (a) {
        this.$refs.anchorNav.clickHandle(a)
      }
    },
    // 获取商品规格属性列表
    attrListChange(val) {
      this.attrList = val
    },
    // 获取购物车数量
    async getCartCount() {
      this.cartProQuantity = await getShoppingCartCount()
    },
    toCartPage() {
      this.$router.push({
        path: '/cart',
        query: { back: 1 }
      })
    },
    handleOpenAttrSelect() {
      /* if (this.detail.productState === '未投产' || this.detail.purchaseHandle === '不可采购') {
        this.errorMsg = `该商品${this.detail.productState}${this.detail.purchaseHandle}，暂时无法加入购物车！`
        this.showError = true
        return
      } */
      if (this.detail.productState === '未投产') {
        this.errorMsg = `该商品${this.detail.productState}${this.detail.purchaseHandle}，暂时无法加入购物车！`
        this.showError = true
        return
      }
      if (this.detail.mdmCode === '' || !this.detail.mdmCode) {
        this.errorMsg = '该商品不是销售产品，暂时无法加入购物车！'
        this.showError = true
        return
      }
      this.showSheet = true
    },
    handleConfirmPop() {
      this.showError = false
      setTimeout(() => {
        if (!this.showError) {
          this.errorMsg = ''
        }
      }, 1000)
    },
    handleAddCartSuccess() {
      this.getCartCount()
      this.showSheet = false
    },
    handleAddCartFail(msg) {
      this.errorMsg = msg || '加入购物车失败'
      this.showError = true
    },
    // 分享处理
    async shareHandle() {
      // 1.验当前产品是否可分享,分享条件：产品状态：在产，采购状态：常规采购 。后台设置是否可分享（上市日期限制）
      // 2.可分享则弹出选择门店弹窗（当前用户所挂门店组织，若只有一个则不弹窗选择门店）
      const shareAble = await checkProductShareAble(this.spuId, this.shareSkuId)
      if (!shareAble) {
        this.$toast('该产品当前不可进行分享')
        return
      }
      const shopList = await getCurrentUserShopList()
      if (shopList.length === 0) {
        this.$toast('当前登录用户无门店组织，不可进行分享')
        return
      }
      this.setShareData(shopList[0])

      this.userShopList = shopList
      if (shopList.length === 1) {
        this.openShare()
        return
      }
      this.$nextTick(() => {
        this.showShopPop = true
      })
    },
    // 设置商品分享数据
    setShareData(shop) {
      const { code, name } = shop
      const { productId, spuName, mdmCode, mdmName, skuId } = this.detail
      const skuObj = this.detail.skus.find(v => v.id === skuId)
      const { skuCode, skuName } = skuObj
      this.shareProductData = {
        // 分享商品数据
        mdmCode,
        mdmName,
        productCode: '',
        productId,
        productName: spuName,
        shopCode: code,
        shopName: name,
        skuId,
        skuCode,
        skuName
      }
    },
    // 打开分享面板
    openShare() {
      this.$nextTick(() => {
        this.showSharePop = true
      })
    },
    // 分享 type: wechat  微信 , friend 朋友圈
    handleShare(type) {
      setShareProduct(this.shareProductData).then(res => {
        const shareDetailId = res.data
        const shareUrl = `${process.env.VUE_APP_SHARE_H5}/share/${shareDetailId}`
        this.shareToWecaht(type, shareUrl)
      })
    },
    async shareToWecaht(type, shareUrl) {
      const pics = this.swipeList.filter(v => v.type === 'image')
      const mainPic = pics.length > 0 ? formatURL(pics[0].picUrl, process.env.VUE_APP_GCENTER_STATIC) || '' : '' // 主图
      // const mainPic = `https://filedev.quanyou.com.cn/marketing/group2/M00/03/A2/rB8kQGP9csqAecQkAAFzZ8JZGuQ960.png` // 主图
      // const mainPic = 'https://gcenterimg.quanyou.com.cn/group1/M00/0B/97/rB8M8GRnEOGAayv7AAsg9eaVR4U878.jpg'
      // const mainPic = 'https://testimg.quanyou.com.cn/group1/M00/01/01/rB8Mk1-ou4mAIGZSAADmIgBk7Is658.jpg'

      let thumbData = ''
      if (mainPic) {
        // 跨域无法转换为base64
        /*  await getBase64(mainPic).then(base64 => {
          // thumbData = base64
        }) */
        // 加t=时间戳：为解决ios13某一个版本图片无法重复onload的问题
        await cutImageBase64(`${mainPic}?t=${new Date().getTime()}`, 120, 'jpg').then(base64 => {
          // console.log(base64)
          thumbData = base64.split('base64,')[1]
        })
      }
      if (!thumbData) {
        this.$toast('图片不存在，无法分享')
        return
      }
      const title = `全友专属家居顾问为您优选产品：${this.detail.spuName}`
      const data = {
        mediaObjectType: 4, // 1文字，2图片，3视频，4网页，5小程序，6音乐视频类
        scene: type === 'friend' ? 1 : 0, // 发送的目标场景,0会话，1朋友圈，2收藏
        message: {
          title, // 消息标题/文本时分享内容
          description: '优选好产品,装满一个家!超值大牌好物,点击查看详情', // 消息描述
          thumbData, // 图片数据/缩略图的二进制数据,应该是除文字外才有,含'data:image/jpg;base64,'比例5:4，且小程序预览图大小不能超过128K
          mediaObject: {
            url: shareUrl
          }
        } // 消息实体
      }
      // console.log('分享唤起参数', JSON.stringify(data))
      this.$nativeHandler('shareToWechat', JSON.stringify(data)).then(res => {
        // dosomething
        this.showSharePop = false
      }).catch(() => {

      })
    }
  }
}
</script>
<style lang="less" scoped>
.detail{
  position: relative;
  padding-bottom: 66PX;
  .content {
    // padding-top: 5px;
    .summary{
      padding: 0 12px;
      background-color: #fff;
      .img-tag{
        // width: 54px;
        height: 16px;
      }
      .tags{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-top: 10px;
        &>*:not(:first-child){
          margin-left: 5px;
        }
        // @media screen and (max-width: 500px) {
        // }
        // @media screen and (min-width: 510px) {
        //   &>:not(:first-child){
        //     margin-left: 45px;
        //   }
        // }
        /deep/.text{
          font-size: 14px;
        }
      }
    }
    .cell-list{
      margin: 10px 0;
      padding: 5px 0;
      background-color: #fff;
      &.mb0{
        margin-bottom: 0;
      }
    }
    .desc{
      &>*{
        margin-top: 10px;
      }
    }
  }
}
.product-bottom-tabbar{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index:9;
  padding:6PX 20PX 20PX;
  height:66PX;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #FFFFFF;
  box-shadow: inset 0px 1px 0px 0px rgba(60,68,88,0.1000);
  backdrop-filter: blur(0px);

  .to-cart-cell{
    position: relative;
    width: 40PX;
    height: 34px;
    .icon-cart{
      width:34PX;
      height: 34PX;
      background: url(~@/assets/icon-cart.png) no-repeat;
      background-size: 100% 100%;
    }
  }
  .btn-add-cart{
    width: 215px;
    height: 40PX;
    background: linear-gradient(90deg, #00D5C0 0%, #05C4C3 100%);
    border-radius: 20PX;
    font-weight: bold;
    font-size: 14PX;
    color: #FFFFFF;
    line-height: 40PX;
    letter-spacing: 1px;
    text-align: center;
  }
}
.spuname_code{
  /deep/ .cell{
    .label{
      width: 70px;
      height: 18px;
      letter-spacing: 1px;
      text-align: justify;
      overflow:hidden;
      // white-space:normal;
      &::after{
        display: inline-block;
        width: 100%;
        content: '';
      }
    }
    .value .text{
      color: #999;
    }
  }
}
.html-content{
  margin-top: 16px;
  padding-top: 10px;
  border-top:1px solid #e6e6e6 ;
  line-height: 1.3;
  font-size: 12px;
  .name{
    font-weight: bold;
    margin-bottom: 6px;
  }
}

.show-window-tips{
  margin-top: 4px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  span{
    display: inline-flex;
    margin-top: 6px;
    padding: 0 4px;
    height: 20px;
    line-height: 20px;
    background: rgba(240, 213, 178, 0.5) ;
    // background: linear-gradient(133deg, rgba(250, 247, 239, 0.5) 0%, rgba(240, 213, 178, 0.5) 46%, rgba(244, 204, 170, 0.5) 100%);
    box-shadow: 0px 0px 9px 0px rgba(176,123,77,0.13), inset -2px -2px 9px 0px rgba(255,255,255,0.29);
    border-radius: 4px;
    font-size: 12px;
    color: #B7854F;
    margin-right: 6px;
  }
}

</style>
